package com.shawn.jetpackstady.lifecycle;

import android.util.Log;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

/**
 * 监听activity或者fragment的生命周期
 */
public class MyLifecycObserver implements LifecycleObserver {
    Lifecycle lifecycle;

    public MyLifecycObserver(Lifecycle lifecycle) {
        this.lifecycle = lifecycle;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void myCreate() {
        Log.i("shawn", "myCreate");
        onCheck();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    private void myStart() {
        Log.i("shawn", "myStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void myResume() {
        Log.i("shawn", "myResume");
        onCheck();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void myPause() {
        Log.i("shawn", "myPause");
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void myStop() {
        Log.i("shawn", "myStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void myDestroy() {
        Log.i("shawn", "myDestroy");
    }

    private void onCheck() {
        // 检查当前生命周期状态
        if (lifecycle.getCurrentState().isAtLeast(Lifecycle.State.CREATED)) {
            Log.i("shawn", "初始化");
        }
        if (lifecycle.getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
            Log.i("shawn", "界面获取焦点");
        }
    }
}
